package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-05-26
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper  contractMapper;
    @Autowired
    private BedMapper bedMapper;
    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 入住申请
     * @param checkInApplyDto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {

        //1.判断老人是否存在 select * from elder where id_card_no = ?
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,checkInApplyDto.getCheckInElderDto().getIdCardNo());
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(elder)) {
            throw new BaseException("该老人已入住");
        }

        //2.更新床位的状态
        //2.1获取床位的id
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();

        //2.2根据id查询床位信息
        Bed bed = bedMapper.selectById(bedId);

        //2.3更新床位状态为已入住
        bed.setBedStatus(1);

        //2.4更新床位信息
        bedMapper.updateById(bed);

        //3.新增或修改老人信息
        elder = insertOrUpdateElder(checkInApplyDto.getCheckInElderDto(),bed);

        //4.保存入住信息
        CheckIn checkIn = saveCheckIn(checkInApplyDto,elder ,bed);

        //5.保存入住配置信息
        saveCheckInConfig(checkInApplyDto.getCheckInConfigDto() , checkIn);

        //6.保存签约办理信息
        saveContract(checkInApplyDto,elder);


    }

    /**
     * 查询入住详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        //1.根据入住信息id查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);

        //2.补全入住配置信息,并进行数据封装
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        //3.根据身份证查询入住老人信息
        CheckInElderVo  checkInElderVo = new CheckInElderVo();
        String idCardNo = checkIn.getIdCardNo();
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,idCardNo);
        Elder elder = elderMapper.selectOne(queryWrapper);
        BeanUtils.copyProperties(elder,checkInElderVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        //4.更具入住信息id查询入住老人家属信息
        List<ElderFamilyVo> list = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(list);

        //5.查询合同信息
        Contract contract = new Contract();
        LambdaQueryWrapper<Contract> contractQueryWrapper = new LambdaQueryWrapper<>();
        contractQueryWrapper.eq(Contract::getElderId,checkIn.getElderId());
        contract = contractMapper.selectOne(contractQueryWrapper);
        checkInDetailVo.setContract(contract);

        //5.封装返回数据并返回
        return checkInDetailVo;

    }

    /**
     * 保存签约办理信息
     * @param checkInApplyDto
     * @param elder
     */
    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract  contract = new Contract();
        //拷贝合同信息
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        //补全老人信息
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        //补全开始时间和结束时间
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //设置合同状态，如果当前时间在开始时间和结束时间之间，则合同状态为已生效，设置值为1
        if (startDate.isBefore(LocalDateTime.now())&& endDate.isAfter(LocalDateTime.now())) {
            contract.setStatus(1);
        }
        //设置合同编号
        String contractNumber = "HT"+ CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNumber);
        contractMapper.insert(contract);

    }

    /**
     * 保存入住配置信息
     * @param checkInConfigDto
     * @param checkIn
     */
    private void saveCheckInConfig(CheckInConfigDto checkInConfigDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        //保存入住配置信息
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 保存入住信息
     * @param checkInApplyDto
     * @param elder
     * @param bed
     * @return
     */
    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
        //1.补全基本信息
        //1.1补全老人信息
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());

        //1.2补全入住信息
        CheckInConfigDto dto = checkInApplyDto.getCheckInConfigDto();
        checkIn.setStartDate(dto.getStartDate());
        checkIn.setEndDate(dto.getEndDate());
        checkIn.setNursingLevelName(dto.getNursingLevelName());

        //1.3补全床位信息
        checkIn.setBedNumber(bed.getBedNumber());

        //1.4补全家属信息
        List<ElderFamilyDto> elderFamilyList = checkInApplyDto.getElderFamilyDtoList();
        if (ObjectUtil.isNotEmpty(elderFamilyList)) {
            checkIn.setRemark(JSON.toJSONString(elderFamilyList));
        }

        //2.保存入住信息并返回
        checkInMapper.insert(checkIn);
        return checkIn;

    }

    /**
     * 新增或修改老人信息
     * @param checkInElderDto
     * @param bed
     * @return
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        Elder elder = new Elder();
        //拷贝老人信息
        BeanUtils.copyProperties(checkInElderDto, elder);
        //更新老人的状态为“1”
        elder.setStatus(1);
        //更新老人的床位Id
        elder.setBedId(bed.getId());
        //更新老人的床位号
        elder.setBedNumber(bed.getBedNumber());
        //查询老人是否存在，根据身份证和状态（状态不为1）
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,elder.getIdCardNo())
                .ne(Elder::getStatus,1);
        Elder elderDoseExist = elderMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(elderDoseExist)) {
            //不为空即老人存在，根据id修改老人信息
            elder.setId(elderDoseExist.getId());
            elderMapper.updateById(elder);
        } else {
            //老人信息不存在，新增老人信息
            elderMapper.insert(elder);
        }
        return elder;
    }
}
